package com.example.demo.permission.user.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.example.demo.common.UserUtil;
import com.example.demo.permission.user.dao.LtUserMapper;
import com.example.demo.permission.user.pojo.LtUser;

// 用户service

@Service
@Transactional
public class LtUserService implements UserDetailsService {

	@Autowired
	LtUserMapper userMapper;

	/**
	 * 判断用户名是否存在
	 */
	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		LtUser user = userMapper.loadUserByUsername(s);
		if (StringUtils.isEmpty(user)) {
			throw new UsernameNotFoundException("用户名不对");
		}
		return user;
	}

	/**
	 * 
	 * 方法描述: 插入用户 --根据用户名判断，如果用户存在就返回-1
	 * 
	 * @param username
	 * @param password
	 * @return
	 * @author lixh
	 */

	public int hrReg(String username, String password) {
		if (userMapper.loadUserByUsername(username) != null) {
			return -1;
		}
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encode = encoder.encode(password);
		return userMapper.hrReg(username, encode);
	}

	/**
	 * 
	 * 方法描述:根据姓名模糊查询
	 * 
	 * @param name
	 * @return
	 * @author lixh
	 */

	public List<LtUser> getHrsByKeywords(String name) {
		return userMapper.getHrsByKeywords(name);
	}

	/**
	 * 
	 * 方法描述: 用户信息更新
	 * 
	 * @param hr
	 * @return
	 * @author lixh
	 */

	public int updateHr(LtUser hr) {
		return userMapper.updateByPrimaryKeySelective(hr);
	}

	public int updateHrRoles(Long hrId, Long[] rids) {
		int reslut = userMapper.deleteRoleByHrId(hrId);
		int reslut2 = userMapper.addRolesForHr(hrId, rids);
		return reslut2;
	}

	/**
	 * 
	 * 方法描述: 根据主键id查询
	 * 
	 * @param hrId
	 * @return
	 * @author lixh
	 */

	public LtUser getHrById(Long hrId) {
		return userMapper.getHrById(hrId);
	}

	/**
	 * 
	 * 方法描述: 根据主键id删除
	 * 
	 * @param hrId
	 * @return
	 * @author lixh
	 */

	public int deleteHr(Long hrId) {
		return userMapper.deleteHr(hrId);
	}

	public List<LtUser> getAllUserExceptAdmin() {
		return userMapper.getAllHr(UserUtil.getCurrentUser().getId().longValue());
	}

	public List<LtUser> getAllHr() {
		return userMapper.getAllHr(null);
	}
}
